package com.example.delivery.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.delivery.pojo.Address;
import com.example.delivery.pojo.User;
import com.example.delivery.service.AddressService;
import com.example.delivery.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;

@Controller
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @Autowired
    private UserService userService;
    @PostMapping("/add")
    public String addAddress(HttpSession session,
                             @RequestParam String address,
                             @RequestParam String contact,
                             @RequestParam String mobile) throws UnsupportedEncodingException {
        // 1. 获取当前用户信息
        String username = (String) session.getAttribute("user");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userName", username);
        User user = userService.getOne(wrapper);

        // 2. 创建地址对象并保存
        Address address1 = new Address();
        address1.setAddress(address);
        address1.setContact(contact);
        address1.setMobile(mobile);
        address1.setZipCode("000000");
        address1.setUserId(Long.valueOf(user.getId()));
        addressService.add(address1);

        // 3. 重定向到支付页面
        return "redirect:/user/checkOut?totalAmount=" + URLEncoder.encode((String) session.getAttribute("totalAmount"), StandardCharsets.UTF_8.name())
                + "&restaurantId=" + URLEncoder.encode((String) session.getAttribute("restaurantId"), StandardCharsets.UTF_8.name());
    }
}
